package com.getpebble.android.framework.datalogging;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import com.getpebble.android.Features;
import com.getpebble.android.Features.Feature;
import com.getpebble.android.common.core.trace.Trace;
import com.getpebble.android.framework.analytics.WatchAnalytics;
import com.getpebble.android.framework.pebblekit.PebbleKit;
import com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage;
import com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage.DataItem;
import com.getpebble.android.framework.protocol.inbound.PblInboundDataloggingMessage.Datatype;
import com.google.common.primitives.UnsignedInteger;
import java.util.LinkedList;
import java.util.List;
import java.util.UUID;

public class DataloggingSession {
    private static final String TAG = DataloggingSession.class.getSimpleName();
    private final UnsignedInteger mAppLogTag;
    private final UUID mAppUuid;
    private final Datatype mDataType;
    private final DataloggingDb mDatabase;
    private boolean mIsFinished;
    private final UnsignedInteger mItemSize;
    private final UUID mLocalSessionUuid;
    private int mNextDataIdSequence;
    private final PebbleKit mPebbleKit;
    private final UnsignedInteger mSessionId;
    private final UnsignedInteger mTimestampSecs;

    DataloggingSession(PblInboundDataloggingMessage message, DataloggingDb database, PebbleKit pebbleKit) throws SQLException {
        if (database == null) {
            throw new IllegalArgumentException("database cannot be null");
        } else if (message == null) {
            throw new IllegalArgumentException("message cannot be null");
        } else if (pebbleKit == null) {
            throw new IllegalArgumentException("pebbleKit cannot be null");
        } else {
            this.mSessionId = message.getSessionId();
            this.mAppUuid = message.getAppUuid();
            this.mTimestampSecs = message.getTimestampSecs();
            this.mAppLogTag = message.getLogTag();
            this.mDataType = message.getDataType();
            this.mItemSize = message.getItemSize();
            this.mLocalSessionUuid = UUID.randomUUID();
            this.mIsFinished = false;
            this.mDatabase = database;
            this.mPebbleKit = pebbleKit;
            this.mNextDataIdSequence = 1;
            log("DataloggingSession() from message");
            this.mDatabase.insertSessionRecord(this);
        }
    }

    DataloggingSession(Cursor cursor, DataloggingDb database, PebbleKit pebbleKit) throws IllegalArgumentException {
        boolean z = true;
        if (database == null) {
            throw new IllegalArgumentException("database cannot be null");
        } else if (cursor == null) {
            throw new IllegalArgumentException("cursor cannot be null");
        } else if (pebbleKit == null) {
            throw new IllegalArgumentException("pebbleKit cannot be null");
        } else {
            this.mSessionId = UnsignedInteger.valueOf(cursor.getLong(cursor.getColumnIndex("session_id")));
            this.mAppUuid = UUID.fromString(cursor.getString(cursor.getColumnIndex("uuid")));
            this.mTimestampSecs = UnsignedInteger.valueOf(cursor.getLong(cursor.getColumnIndex("timestamp")));
            this.mAppLogTag = UnsignedInteger.valueOf(cursor.getLong(cursor.getColumnIndex("app_log_tag")));
            this.mDataType = Datatype.fromCode((byte) cursor.getInt(cursor.getColumnIndex("data_type")));
            this.mItemSize = UnsignedInteger.valueOf(cursor.getLong(cursor.getColumnIndex("item_size")));
            this.mLocalSessionUuid = UUID.fromString(cursor.getString(cursor.getColumnIndex("local_session_uuid")));
            if (cursor.getInt(cursor.getColumnIndex("is_finished")) != 1) {
                z = false;
            }
            this.mIsFinished = z;
            this.mNextDataIdSequence = cursor.getInt(cursor.getColumnIndex("next_data_id_sequence"));
            this.mDatabase = database;
            this.mPebbleKit = pebbleKit;
            log("DataloggingSession() from cursor");
        }
    }

    void close() {
        log("close()");
        this.mIsFinished = true;
        updateDatabase();
        checkComplete();
    }

    boolean checkComplete() {
        if (!this.mIsFinished || this.mDatabase.loadItemsForSession(this).size() != 0) {
            return false;
        }
        log("Session complete (empty + no items)");
        this.mPebbleKit.broadcastDataloggingCloseSession(this);
        return true;
    }

    List<DataloggingItem> addData(List<DataItem> data) throws SQLException {
        log("addData() size = " + data.size());
        List<DataloggingItem> items = new LinkedList();
        if (Features.getWatchAnalytics() == Feature.OFF && getAppUuid().equals(WatchAnalytics.WATCH_ANALYTICS_APP_UUID)) {
            log("Ignoring watch analytics message");
        } else {
            boolean closeSession = false;
            for (DataItem item : data) {
                int sequence = getNextDataIdSequence();
                if (sequence >= 2147478647) {
                    closeSession = true;
                }
                items.add(getItemRecord(item, sequence));
            }
            if (closeSession) {
                log("Session reached max data item sequence; closing");
                close();
            }
        }
        return items;
    }

    protected DataloggingItem getItemRecord(DataItem item, int dataId) throws SQLException {
        return new DataloggingItem(this, item, this.mDatabase, this.mPebbleKit, dataId);
    }

    void ackItem(int dataId) {
        log("ackItem() dataId = " + dataId);
        DataloggingItem item = this.mDatabase.loadItem(this, dataId);
        if (item == null) {
            log("ackItem() item not found with dataId = " + dataId);
            return;
        }
        item.ack();
        checkComplete();
    }

    void broadcastData() {
        log("broadcastData()");
        for (DataloggingItem item : this.mDatabase.loadItemsForSession(this)) {
            item.broadcast();
        }
    }

    private void updateDatabase() {
        log("updateDatabase()");
        this.mDatabase.updateSessionRecord(this);
    }

    ContentValues getContentValues() {
        ContentValues values = new ContentValues();
        values.put("session_id", Long.valueOf(this.mSessionId.longValue()));
        values.put("uuid", this.mAppUuid.toString());
        values.put("timestamp", Long.valueOf(this.mTimestampSecs.longValue()));
        values.put("app_log_tag", Long.valueOf(this.mAppLogTag.longValue()));
        values.put("data_type", Integer.valueOf(this.mDataType.getCode()));
        values.put("item_size", Long.valueOf(this.mItemSize.longValue()));
        values.put("local_session_uuid", this.mLocalSessionUuid.toString());
        values.put("is_finished", Integer.valueOf(this.mIsFinished ? 1 : 0));
        values.put("next_data_id_sequence", Integer.valueOf(this.mNextDataIdSequence));
        return values;
    }

    public UUID getLocalSessionUuid() {
        return this.mLocalSessionUuid;
    }

    public UUID getAppUuid() {
        return this.mAppUuid;
    }

    public UnsignedInteger getTimestampSecs() {
        return this.mTimestampSecs;
    }

    public UnsignedInteger getAppLogTag() {
        return this.mAppLogTag;
    }

    UnsignedInteger getSessionId() {
        return this.mSessionId;
    }

    UnsignedInteger getItemSize() {
        return this.mItemSize;
    }

    public Datatype getDataType() {
        return this.mDataType;
    }

    int getNextDataIdSequence() {
        int nextSequence = this.mNextDataIdSequence;
        this.mNextDataIdSequence = nextSequence + 1;
        updateDatabase();
        return nextSequence;
    }

    boolean isFinished() {
        return this.mIsFinished;
    }

    boolean matchesSessionParameters(PblInboundDataloggingMessage otherParams) {
        if (!getSessionId().equals(otherParams.getSessionId())) {
            log("session id mismatch: " + getSessionId() + " != " + otherParams.getSessionId());
            return false;
        } else if (!getAppUuid().equals(otherParams.getAppUuid())) {
            log("app uuid mismatch: " + getAppUuid() + " != " + otherParams.getAppUuid());
            return false;
        } else if (!getTimestampSecs().equals(otherParams.getTimestampSecs())) {
            log("timestamp mismatch: " + getTimestampSecs() + " != " + otherParams.getTimestampSecs());
            return false;
        } else if (!getAppLogTag().equals(otherParams.getLogTag())) {
            log("app log tag mismatch: " + getAppLogTag() + " != " + otherParams.getLogTag());
            return false;
        } else if (!getDataType().equals(otherParams.getDataType())) {
            log("data type mismatch: " + getDataType() + " != " + otherParams.getDataType());
            return false;
        } else if (getItemSize().equals(otherParams.getItemSize())) {
            return true;
        } else {
            log("item size mismatch: " + getItemSize() + " != " + otherParams.getItemSize());
            return false;
        }
    }

    public String toString() {
        return "[sessionId = " + getSessionId() + "; appUuid = " + getAppUuid() + "; timestamp = " + getTimestampSecs() + "; appLogTag = " + getAppLogTag() + "; dataType = " + getDataType() + "; itemSize = " + getItemSize() + "; localSessionUuid = " + getLocalSessionUuid() + "; isFinished = " + isFinished();
    }

    private void log(String message) {
        Trace.verbose(TAG, getSessionId() + " / " + getLocalSessionUuid() + ": " + message);
    }
}
